#include "gamephasecontroller.h"
#include <QPainter>
#include <QTimer>

GamePhaseController::GamePhaseController(QGraphicsItem* parent, PlayerTable* t)
    :QGraphicsObject(parent), table(t)
{
    setPos(400, 200);
    //_pix = QPixmap(":/pmachine/images/pmachine_background.png");
    createMachine();
    createState();
    machine->start();
}

GamePhaseController::~GamePhaseController(){
    delete machine;
}

QRectF GamePhaseController::boundingRect() const{
    return QRectF(-CONTROL_WIDTH/2, -CONTROL_HEIGHT/2, CONTROL_WIDTH, CONTROL_HEIGHT);
}

void GamePhaseController::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
    painter->fillRect(boundingRect(), Qt::white);
    painter->drawRect(boundingRect());
    painter->drawText(boundingRect(), Qt::AlignCenter, c_phase);
}

void GamePhaseController::createMachine(){
    machine = new QStateMachine();
}

void GamePhaseController::createState(){
    QState* root = new QState;
    QState* turn_start = new QState(root);
    QState* ghost_act = new QState(root);
    QState* ghost_arrival = new QState(root);
    QState* taoist_act = new QState(root);
    QState* turn_finish = new QState(root);

    turn_start->assignProperty(this, "phase", TURN_START);
    turn_start->addTransition(this, SIGNAL(TURN_START_PAUSE()), ghost_act);

    ghost_act->assignProperty(this, "phase", GHOST_ACT);
    ghost_act->addTransition(table, SIGNAL(phaseChange()), ghost_arrival);

    ghost_arrival->assignProperty(this, "phase", GHOST_ARR);
    ghost_arrival->addTransition(table, SIGNAL(phaseChange()), taoist_act);

    taoist_act->assignProperty(this, "phase", TAO_ACT);
    taoist_act->addTransition(table, SIGNAL(phaseChange()), turn_finish);

    turn_finish->assignProperty(this, "phase", TURN_FIN);
    turn_finish->addTransition(table, SIGNAL(phaseChange()), turn_start);

    machine->addState(root);
    machine->setInitialState(root);
    root->setInitialState(turn_start);

}


void GamePhaseController::setPhase(GAME_PHASE p){
    _phase = p;
    switch(_phase){
    case TURN_START:
        QTimer::singleShot(1000, this, SIGNAL(TURN_START_PAUSE()));
        c_phase = "Turn Start";
        break;
    case GHOST_ACT:
        c_phase = "Ghost Action";
        break;
    case GHOST_ARR:
        break;
    case TAO_ACT:
        break;
    case TURN_FIN:
        break;
    }
    update();
}
